<template>
	<view class="chatInterface" @contextmenu.prevent="">

		<scroll-view class="scroll-view" scroll-y :scroll-into-view="scrollToView" :scroll-with-animation="true"
			@scrolltoupper="onScrollToUpper" @scroll="onScroll" @refresherrefresh="onRefresh"
			@refresherrestore="onRestoreRefresh">
			<image class="group-icon" src="/static/images/group-icon.png" @click="showMembers" />
			<!-- 将水印容器移到这里 -->
			<view class="watermark-container" v-if="isSy">
				<view class="watermark-grid">
					<text v-for="i in 1000" :key="i" class="watermark-text">订单已确认</text>
				</view>
			</view>

			<view class="chat-content">
				<image v-if="history.loading" class="history-loaded" src="/static/images/loading.svg" />
				<view v-else :class="history.allLoaded ? 'history-loaded':'load'" @click="loadHistoryMessage(false)">
					<view>{{ history.allLoaded ? '已经没有更多的历史消息' : '点击获取历史消息' }}</view>
				</view>

				<checkbox-group @change="selectMessages">
					<view v-for="(message,index) in history.messages" :key="message.messageId" :id="'msg_' + index">
						<!--时间显示，类似于微信，隔5分钟不发言，才显示时间-->
						<view class="time-lag">
							{{ renderMessageDate(message, index) }}
						</view>
						<view class="message-recalled" v-if="message.recalled">
							<view v-if="message.recaller.id == currentUser.id" class="message-recalled-self">
								<view>你撤回了一条消息</view>
								<span v-if="message.type === 'text' && Date.now()-message.timestamp< 60 * 1000 "
									@click="editRecalledMessage(message.payload.text)">重新编辑</span>
							</view>
							<view v-else>{{ message.recaller.data.name }}撤回了一条消息</view>
						</view>
						<view class="message-item" v-else>
							<view class="message-item-checkbox">
								<checkbox v-show="messageSelector.visible && message.status !== 'sending'"
									:value="message.messageId" :checked="messageSelector.messages.includes(message)" />
							</view>
							<view class="message-item-content" :class="{'self' : message.senderId ==  currentUser.id}">
								<view class="avatar">
									<image :src="message.senderData.avatar"></image>
								</view>

								<view class="content" @click.right="showActionPopup(message)"
									@longpress="showActionPopup(message)">
									<view v-if="message.senderId == currentUser.id" class="contentName">
										{{message.senderData.name}}
									</view>
									<view v-else class="contentName" style="text-align: left;">
										{{message.senderData.name }}
									</view>
									<view class="message-payload">
										<b class="pending" v-if="message.status === 'sending'"></b>
										<b class="send-fail" v-if="message.status === 'fail'"></b>
										<view v-if="message.type === 'text'" class="text-content"
											v-html="renderTextMessage(message)"></view>
										<image v-if="message.type === 'image'" :data-url="message.payload.url"
											:src="message.payload.thumbnail" @load="handleImgLoad" class="image-content"
											mode="widthFix" @click="showImageFullScreen"></image>
										<image v-if="message.type === 'newImage'" @load="handleImgLoad"
											class="image-content" mode="widthFix" :data-url="message.payload.image"
											:src="message.payload.image" @click="showImageFullScreen"></image>
										<view class="enterOrder" v-if="message.type === 'enterOrder'">
											<view class="header">
												<view class="lf">
													<image class="msg-icon"
														src="/static/images/order-enter-msg-icon.png" mode="">
													</image>
													<text>订单已确认</text>
												</view>
												<view class="time">{{message.payload.time}}</view>
											</view>
											<view class="content">
												<view class="col">
													<image class="msg-icon" style="width: 36rpx;height: 36rpx;"
														src="/static/images/orderid-icon.png" mode=""></image>
													<text class="label">订单号:</text>
													<text class="val">{{message.payload.orderId}}</text>
												</view>
												<view class="col">
													<image class="msg-icon" src="/static/images/time-icon.png" mode="">
													</image>
													<text class="label">确认时间:</text>
													<text class="val">{{message.payload.time}}</text>
												</view>
											</view>
										</view>
										<view class="video-snapshot" v-if="message.type === 'video'"
											:data-url="message.payload.video.url" @click="playVideo">
											<image :src="message.payload.thumbnail.url"
												:style="{height: getImageHeight(message.payload.thumbnail.width,message.payload.thumbnail.height)+'rpx' }"
												mode="heightFix"></image>
											<view class="video-play-icon"></view>
										</view>
										<view class="file-content" v-if="message.type === 'file'">
											<view class="file-info">
												<span class="file-name">{{ message.payload.name }}</span>
												<span
													class="file-size">{{ (message.payload.size / 1024).toFixed(2) }}KB</span>
											</view>
											<image class="file-img" src="/static/images/file-icon.png"></image>
										</view>
										<view v-if="message.type ==='audio'" class="audio-content"
											@click="playAudio(message)">
											<view class="audio-facade"
												:style="{width:Math.ceil(message.payload.duration)*7 + 50 + 'px'}">
												<view class="audio-facade-bg"
													:class="{'play-icon':audioPlayer.playingMessage && audioPlayer.playingMessage.messageId === message.messageId}">
												</view>
												<view>{{Math.ceil(message.payload.duration) || 1}}<span>"</span></view>
											</view>
										</view>
										<view v-if="message.type === 'order'" class="order-content">
											<view class="order-id">订单号：{{ message.payload.id }}</view>
											<view class="order-body">
												<image :src="message.payload.url" class="order-img"></image>
												<view>
													<view class="order-name">{{ message.payload.name }}</view>
													<view class="order-info">
														<view class="order-price">{{ message.payload.price }}</view>
														<view class="order-count">共{{ message.payload.count }}件</view>
													</view>
												</view>
											</view>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
					<view class="scroll-bottom-placeholder" :id="'msg_' + history.messages.length"></view>
				</checkbox-group>
			</view>
		</scroll-view>

		<view class="action-box" v-if="!videoPlayer.visible && !messageSelector.visible">
			<view class="action-top">
				<view @click="switchAudioKeyboard">
					<image class="more" v-if="audio.visible" src="/static/images/jianpan.png"></image>
					<image class="more" v-else src="/static/images/audio.png"></image>
				</view>
				<view v-if="audio.visible" class="record-input" @touchend.stop="onRecordEnd"
					@touchstart.stop="onRecordStart">
					{{ recorderManager.recording ? '松开发送' : '按住录音' }}
				</view>
				<!-- GoEasyIM最大支持3k的文本消息，如需发送长文本，需调整输入框maxlength值 -->
				<input v-else v-model="text" @confirm="sendTextMessage" class="consult-input" maxlength="700"
					placeholder="发送消息" type="text" />
				<view v-if="isQd"
					style="display: flex;flex-direction: column;justify-content: center;align-items: center;font-size: 28rpx;">
					<image @click="handleEnterOrder" class="more enter-icon"
						src="/static/images/order-enter-icon.png" />
					<text>订单确认</text>
				</view>
				<view @click="switchEmojiKeyboard">
					<image class="more" v-if="emoji.visible" src="/static/images/jianpan.png"></image>
					<image class="more" v-else src="/static/images/emoji.png"></image>
				</view>
				<view>
					<image @click="showOtherTypesMessagePanel()" class="more" src="/static/images/more.png" />
				</view>
				<view v-if="text" class="send-btn-box">
					<text class="btn" @click="sendTextMessage()">发送</text>
				</view>
			</view>
			<view class="action-bottom action-bottom-emoji" v-if="emoji.visible">
				<image class="emoji-item" v-for="(emojiItem, key, index) in emoji.map" :key="index"
					:src="emoji.url + emojiItem" @click="chooseEmoji(key)"></image>
			</view>
			<!--其他类型消息面板-->
			<view v-if="otherTypesMessagePanelVisible" class="action-bottom">
				<view class="more-icon">
					<image @click="sendImageMessage()" class="operation-icon" src="/static/images/picture.png">
					</image>
					<view class="operation-title">图片</view>
				</view>
				<!-- 	<view class="more-icon">
					<image @click="sendVideoMessage()" class="operation-icon" src="/static/images/video.png"></image>
					<view class="operation-title">视频</view>
				</view> -->
				<!-- <view class="more-icon">
					<image @click="showOrderMessageList()" class="operation-icon" src="/static/images/order.png">
					</image>
					<view class="operation-title">订单</view>
				</view> -->
				<!-- <view class="more-icon">
					<image @click="groupCall()" class="operation-icon" src="/static/images/video.png"></image>
					<view class="operation-title">视频通话</view>
				</view> -->
			</view>
		</view>
		<view class="action-popup" @touchmove.stop.prevent v-if="actionPopup.visible">
			<view class="layer"></view>
			<view class="action-list">
				<view class="action-item" @click="handleDownloadImg">下载</view>
				<view class="action-item" @click="deleteSingleMessage">删除</view>
				<view class="action-item" v-if="actionPopup.recallable" @click="recallMessage">撤回</view>
				<view class="action-item" @click="showCheckBox">多选</view>
				<view class="action-item" @click="hideActionPopup">取消</view>
			</view>
		</view>
		<view class="messageSelector-box" v-if="messageSelector.visible">
			<image class="messageSelector-btn" @click="deleteMultipleMessages" src="/static/images/delete.png">
			</image>
		</view>
		<view class="record-loading" v-if="recorderManager.recording"></view>
		<video v-if="videoPlayer.visible" :src="videoPlayer.url" id="videoPlayer"
			@fullscreenchange="onVideoFullScreenChange"></video>
		<view v-if="orderList.visible" class="order-list">
			<view class="orders-content">
				<view class="title">
					<view>请选择一个订单</view>
					<view class="close" @click="hideOrderMessageList">×</view>
				</view>
				<view class="orders">
					<view v-for="(order, index) in orderList.orders" :key="index" class="order-item"
						@click="sendOrderMessage(order)">
						<view class="order-id">订单号：{{ order.id }}</view>
						<view class="order-body">
							<image :src="order.url" class="order-img"></image>
							<view class="order-name">{{ order.name }}</view>
							<view class="order-right">
								<view class="order-price">{{ order.price }}</view>
								<view class="order-count">共{{ order.count }}件</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import EmojiDecoder from '../lib/EmojiDecoder';
	import restApi, {
		getOrderDateilsAPI,
		getStoreIamgeListAPI,
		uploadImagesAPI,
		setOrderQdAPI
	} from '../lib/restapi';
	import {
		formatDate
	} from '../lib/utils';
	import RecorderManager from '../lib/RecorderManager';
	import {
		BASE_URL
	} from '../request/config';

	const IMAGE_MAX_WIDTH = 200;
	const IMAGE_MAX_HEIGHT = 150;
	const recorderManager = new RecorderManager();
	const GoEasy = uni.$GoEasy;
	export default {
		name: 'groupChat',
		data() {
			// 定义表情
			const emojiUrl = 'https://imgcache.qq.com/open/qcloud/tim/assets/emoji/';
			const emojiMap = {
				'[NO]': 'emoji_0@2x.png',
				'[OK]': 'emoji_1@2x.png',
				'[下雨]': 'emoji_2@2x.png',
				'[么么哒]': 'emoji_3@2x.png',
				'[乒乓]': 'emoji_4@2x.png',
				'[便便]': 'emoji_5@2x.png',
				'[信封]': 'emoji_6@2x.png',
				'[偷笑]': 'emoji_7@2x.png',
				'[傲慢]': 'emoji_8@2x.png',
				'[再见]': 'emoji_9@2x.png',
				'[冷汗]': 'emoji_10@2x.png',
				'[凋谢]': 'emoji_11@2x.png',
				'[刀]': 'emoji_12@2x.png',
				'[删除]': 'emoji_13@2x.png',
				'[勾引]': 'emoji_14@2x.png',
				'[发呆]': 'emoji_15@2x.png',
				'[发抖]': 'emoji_16@2x.png',
				'[可怜]': 'emoji_17@2x.png',
				'[可爱]': 'emoji_18@2x.png',
				'[右哼哼]': 'emoji_19@2x.png',
				'[右太极]': 'emoji_20@2x.png',
				'[右车头]': 'emoji_21@2x.png',
				'[吐]': 'emoji_22@2x.png',
				'[吓]': 'emoji_23@2x.png',
				'[咒骂]': 'emoji_24@2x.png',
				'[咖啡]': 'emoji_25@2x.png',
				'[啤酒]': 'emoji_26@2x.png',
				'[嘘]': 'emoji_27@2x.png',
				'[回头]': 'emoji_28@2x.png',
				'[困]': 'emoji_29@2x.png',
				'[坏笑]': 'emoji_30@2x.png',
				'[多云]': 'emoji_31@2x.png',
				'[大兵]': 'emoji_32@2x.png',
				'[大哭]': 'emoji_33@2x.png',
				'[太阳]': 'emoji_34@2x.png',
				'[奋斗]': 'emoji_35@2x.png',
				'[奶瓶]': 'emoji_36@2x.png',
				'[委屈]': 'emoji_37@2x.png',
				'[害羞]': 'emoji_38@2x.png',
				'[尴尬]': 'emoji_39@2x.png',
				'[左哼哼]': 'emoji_40@2x.png',
				'[左太极]': 'emoji_41@2x.png',
				'[左车头]': 'emoji_42@2x.png',
				'[差劲]': 'emoji_43@2x.png',
				'[弱]': 'emoji_44@2x.png',
				'[强]': 'emoji_45@2x.png',
				'[彩带]': 'emoji_46@2x.png',
				'[彩球]': 'emoji_47@2x.png',
				'[得意]': 'emoji_48@2x.png',
				'[微笑]': 'emoji_49@2x.png',
				'[心碎了]': 'emoji_50@2x.png',
				'[快哭了]': 'emoji_51@2x.png',
				'[怄火]': 'emoji_52@2x.png',
				'[怒]': 'emoji_53@2x.png',
				'[惊恐]': 'emoji_54@2x.png',
				'[惊讶]': 'emoji_55@2x.png',
				'[憨笑]': 'emoji_56@2x.png',
				'[手枪]': 'emoji_57@2x.png',
				'[打哈欠]': 'emoji_58@2x.png',
				'[抓狂]': 'emoji_59@2x.png',
				'[折磨]': 'emoji_60@2x.png',
				'[抠鼻]': 'emoji_61@2x.png',
				'[抱抱]': 'emoji_62@2x.png',
				'[抱拳]': 'emoji_63@2x.png',
				'[拳头]': 'emoji_64@2x.png',
				'[挥手]': 'emoji_65@2x.png',
				'[握手]': 'emoji_66@2x.png',
				'[撇嘴]': 'emoji_67@2x.png',
				'[擦汗]': 'emoji_68@2x.png',
				'[敲打]': 'emoji_69@2x.png',
				'[晕]': 'emoji_70@2x.png',
				'[月亮]': 'emoji_71@2x.png',
				'[棒棒糖]': 'emoji_72@2x.png',
				'[汽车]': 'emoji_73@2x.png',
				'[沙发]': 'emoji_74@2x.png',
				'[流汗]': 'emoji_75@2x.png',
				'[流泪]': 'emoji_76@2x.png',
				'[激动]': 'emoji_77@2x.png',
				'[灯泡]': 'emoji_78@2x.png',
				'[炸弹]': 'emoji_79@2x.png',
				'[熊猫]': 'emoji_80@2x.png',
				'[爆筋]': 'emoji_81@2x.png',
				'[爱你]': 'emoji_82@2x.png',
				'[爱心]': 'emoji_83@2x.png',
				'[爱情]': 'emoji_84@2x.png',
				'[猪头]': 'emoji_85@2x.png',
				'[猫咪]': 'emoji_86@2x.png',
				'[献吻]': 'emoji_87@2x.png',
				'[玫瑰]': 'emoji_88@2x.png',
				'[瓢虫]': 'emoji_89@2x.png',
				'[疑问]': 'emoji_90@2x.png',
				'[白眼]': 'emoji_91@2x.png',
				'[皮球]': 'emoji_92@2x.png',
				'[睡觉]': 'emoji_93@2x.png',
				'[磕头]': 'emoji_94@2x.png',
				'[示爱]': 'emoji_95@2x.png',
				'[礼品袋]': 'emoji_96@2x.png',
				'[礼物]': 'emoji_97@2x.png',
				'[篮球]': 'emoji_98@2x.png',
				'[米饭]': 'emoji_99@2x.png',
				'[糗大了]': 'emoji_100@2x.png',
				'[红双喜]': 'emoji_101@2x.png',
				'[红灯笼]': 'emoji_102@2x.png',
				'[纸巾]': 'emoji_103@2x.png',
				'[胜利]': 'emoji_104@2x.png',
				'[色]': 'emoji_105@2x.png',
				'[药]': 'emoji_106@2x.png',
				'[菜刀]': 'emoji_107@2x.png',
				'[蛋糕]': 'emoji_108@2x.png',
				'[蜡烛]': 'emoji_109@2x.png',
				'[街舞]': 'emoji_110@2x.png',
				'[衰]': 'emoji_111@2x.png',
				'[西瓜]': 'emoji_112@2x.png',
				'[调皮]': 'emoji_113@2x.png',
				'[象棋]': 'emoji_114@2x.png',
				'[跳绳]': 'emoji_115@2x.png',
				'[跳跳]': 'emoji_116@2x.png',
				'[车厢]': 'emoji_117@2x.png',
				'[转圈]': 'emoji_118@2x.png',
				'[鄙视]': 'emoji_119@2x.png',
				'[酷]': 'emoji_120@2x.png',
				'[钞票]': 'emoji_121@2x.png',
				'[钻戒]': 'emoji_122@2x.png',
				'[闪电]': 'emoji_123@2x.png',
				'[闭嘴]': 'emoji_124@2x.png',
				'[闹钟]': 'emoji_125@2x.png',
				'[阴险]': 'emoji_126@2x.png',
				'[难过]': 'emoji_127@2x.png',
				'[雨伞]': 'emoji_128@2x.png',
				'[青蛙]': 'emoji_129@2x.png',
				'[面条]': 'emoji_130@2x.png',
				'[鞭炮]': 'emoji_131@2x.png',
				'[风车]': 'emoji_132@2x.png',
				'[飞吻]': 'emoji_133@2x.png',
				'[飞机]': 'emoji_134@2x.png',
				'[饥饿]': 'emoji_135@2x.png',
				'[香蕉]': 'emoji_136@2x.png',
				'[骷髅]': 'emoji_137@2x.png',
				'[麦克风]': 'emoji_138@2x.png',
				'[麻将]': 'emoji_139@2x.png',
				'[鼓掌]': 'emoji_140@2x.png',
				'[龇牙]': 'emoji_141@2x.png'
			};
			return {
				//聊天文本框
				text: '',
				group: null,
				to: {}, // 作为createMessage的参数
				currentUser: null,

				scrollTop: 0,
				isRefreshing: false,
				lastScrollTop: 0,
				isLoadingMore: false,
				lastContentHeight: 0,

				//定义表情列表
				emoji: {
					url: emojiUrl,
					map: emojiMap,
					visible: false,
					decoder: new EmojiDecoder(emojiUrl, emojiMap),
				},
				//是否展示‘其他消息类型面板’
				otherTypesMessagePanelVisible: false,
				orderList: {
					orders: [],
					visible: false
				},
				history: {
					messages: [],
					allLoaded: false,
					loading: false
				},
				recorderManager: recorderManager,
				audio: {
					//录音按钮展示
					visible: false
				},
				audioPlayer: {
					innerAudioContext: null,
					playingMessage: null,
				},
				videoPlayer: {
					visible: false,
					url: '',
					context: null
				},
				// 展示消息删除弹出框
				actionPopup: {
					visible: false,
					message: null,
					recallable: false,
				},
				// 消息选择
				messageSelector: {
					visible: false,
					messages: []
				},
				isQd: false,
				isSy: false,
				scrollToView: '',
				// isSendImg: false
			}
		},
		async onLoad(options) {
			//聊天对象
			let id = options.to;
			const type = options.type
			// 获取当前用户
			this.currentUser = uni.getStorageSync("currentUser") ? uni.getStorageSync("currentUser") : uni
				.$currentUser;
			await restApi.fetchGetGourpListAPI({
				id: this.currentUser.id
			})
			await this.handleShowEnterOrder(id)
			// 获取当前的群聊
			this.group = restApi.findGroupById(id) ? restApi.findGroupById(id) : id ? {
				id
			} : {};

			if (GoEasy.getConnectionStatus() === 'disconnected') {
				this.connectGoEasy(); //连接goeasy
				this.subscribeGroup(); //建立连接后，就应该订阅群聊消息，避免漏掉
			}
			// 获取当前群聊人数
			this.groupMembers = restApi.findGroupMembers(this.group?.id);
			// 当前的个人资料 用户发送消息时携带的
			this.to = {
				id: this.group?.id,
				type: GoEasy.IM_SCENE.GROUP,
				data: {
					name: this.group?.name,
					avatar: this.group?.avatar
				}
			};

			// 监听当前群聊消息 (订阅群消息) 主要是推送消息和删除消息等
			this.initGoEasyListeners();
			// 语音播放器
			this.initialAudioPlayer();
			// 录音监听器
			this.initRecorderListeners();
			// 图像类型
			const imgType = ['original', 'finish']
			// 如果有类型时
			if (type) {
				// 是否一键发送照片
				const isSend = imgType.includes(type)
				if (isSend) {
					this.sendHandleImg({
						id: this.currentUser.id,
						groupId: id,
						type
					})
				}
			}
			this.loadHistoryMessage(true);
			this.videoPlayer.context = uni.createVideoContext('videoPlayer', this);
			uni.setNavigationBarTitle({
				title: this.group?.name + '（' + Object.keys(this.groupMembers).length + '）'
			});
		},
		onShow() {
			this.otherTypesMessagePanelVisible = false;
			this.emoji.visible = false;
		},
		mounted() {
			const that = this
			this.scrollToView = ''
			this.$nextTick(() => {
				that.scrollToBottom();
			});
		},
		onPullDownRefresh(e) {
			this.loadHistoryMessage(false);
		},
		onUnload() {
			//退出聊天页面之前，清空监听器
			GoEasy.im.off(GoEasy.IM_EVENT.GROUP_MESSAGE_RECEIVED, this.onMessageReceived);
			GoEasy.im.off(GoEasy.IM_EVENT.MESSAGE_DELETED, this.onMessageDeleted);
		},
		methods: {
			handleImgLoad() { // 解决图片加载问题
				// 坑点: 因为图片加载是异步的 当图片加载完毕后 滚动条会滚动到图片区域 导致加载一直不能到达底部区域
				this.scrollToView = ''
				this.scrollToBottom()
			},
			// 处理滚动到顶部事件
			onScrollToUpper() {
				if (!this.isLoadingMore && !this.history.allLoaded) {
					this.loadHistoryMessage(false);
				}
			},
			// 处理滚动事件
			onScroll(e) {
				this.lastScrollTop = e.detail.scrollTop;
			},
			// 处理下拉刷新
			async onRefresh() {
				if (this.isLoadingMore) return;

				this.isRefreshing = true;
				await this.loadHistoryMessage(false);
				this.isRefreshing = false;
			},
			// 处理刷新恢复
			onRestoreRefresh() {
				this.isRefreshing = false;
			},
			connectGoEasy() {
				GoEasy.connect({
					id: this.currentUser.id,
					data: {
						name: this.currentUser.name,
						avatar: this.currentUser.avatar
					},
					onSuccess: () => {
						console.log('GoEasy connect successfully.')
					},
					onFailed: (error) => {
						console.log('Failed to connect GoEasy, code:' + error.code + ',error:' + error
							.content);
					},
					onProgress: (attempts) => {
						console.log('GoEasy is connecting', attempts);
					}
				});
			},
			subscribeGroup() {
				let groups = restApi.findGroups(this.currentUser);
				let groupIds = groups.map(item => item.id);
				GoEasy.im.subscribeGroup({
					groupIds: groupIds,
					onSuccess: function() {
						console.log('订阅群消息成功');
					},
					onFailed: function(error) {
						console.log('订阅群消息失败:', error);
					}
				});
			},
			async handleShowEnterOrder(id) {
				const {
					data,
					status
				} = await getOrderDateilsAPI({
					id
				})
				if (status) {
					const {
						isPs,
						isQd,
						isTag
					} = data

					// 只有是修图订单 并且isQd并且还未确定的时候 才现实确定订单的操作按钮
					if (Boolean(data.isPs) && Boolean(data.isQd)) {
						this.isQd = true
					}

					if (Boolean(data.isPs) && Boolean(data.isTag) && !Boolean(data.isQd)) {
						this.isSy = true
					}
				}
			},
			async sendHandleImg({
				id,
				groupId,
				type
			}) {
				const {
					status,
					data
				} = await getStoreIamgeListAPI({
					id, //用户编码
					groupId, //群聊编码
					type //图片类型（original、finish）
				})
				if (status) {
					console.log(data);
				}
			},
			handleEnterOrder() { // 订单确认
				const groupId = this.group.id
				const that = this
				uni.showModal({
					title: '是否确认订单完成',
					success(res) {
						if (res.confirm) {
							const data = setOrderQdAPI({
								id: groupId
							}).then(({
								data,
								status,
								msg
							}) => {
								if (status) {
									that.isQd = false
									that.isSy = true
									const time = new Date()
									const h = that.handleTimeFormate(time.getHours())
									const m = that.handleTimeFormate(time.getMinutes())
									// 发送消息
									that.handleTypeSend('enterOrder', {
										orderId: that.group.id,
										time: `${h}:${m}`
									})
								} else {
									uni.showToast({
										title: msg

									})
								}
							})
						}
					}
				})
			},
			handleTimeFormate(num) {
				return String(num).padStart(2, '0')
			},
			handleTypeSend(type, payload) {
				const that = this
				GoEasy.im.createCustomMessage({
					type, //消息类型
					payload,
					notification: {
						title: that.currentUser.name + '用户订单已确认',
						body: `[订单确认]`, // 字段最长 50 字符
						sound: 'message',
						badge: '+1'
					},
					to: that.to,
					onSuccess: (message) => {
						that.sendMessage(message);
					},
				});
			},
			//渲染文本消息，如果包含表情，替换为图片
			//todo:本不需要该方法，可以在标签里完成，但小程序有兼容性问题，被迫这样实现
			renderTextMessage(message) {
				return '<span>' + this.emoji.decoder.decode(message.payload.text) + '</span>';
			},
			//像微信那样显示时间，如果有几分钟没发消息了，才显示时间
			//todo:本不需要该方法，可以在标签里完成，但小程序有兼容性问题，被迫这样实现
			renderMessageDate(message, index) {
				if (index === 0) {
					return formatDate(message.timestamp)
				} else {
					if (message.timestamp - this.history.messages[index - 1].timestamp > 5 * 60 * 1000) {
						return formatDate(message.timestamp)
					}
				}
				return '';
			},
			initGoEasyListeners() {
				// 监听群聊消息
				GoEasy.im.on(GoEasy.IM_EVENT.GROUP_MESSAGE_RECEIVED, this.onMessageReceived);
				//监听消息删除
				GoEasy.im.on(GoEasy.IM_EVENT.MESSAGE_DELETED, this.onMessageDeleted);
			},
			onMessageReceived(message) {
				let groupId = message.groupId;
				if (groupId === this.group.id) {
					this.history.messages.push(message);
					//聊天时，收到消息标记为已读
					this.markGroupMessageAsRead();
					//收到新消息，是滚动到最底部
					this.scrollToBottom();
				}
			},
			onMessageDeleted(deletedMessages) {
				deletedMessages.forEach(message => {
					let groupId = message.groupId;
					if (groupId && groupId === this.group.id) {
						let index = this.history.messages.indexOf(message);
						if (index > -1) {
							this.history.messages.splice(index, 1);
						}
					}
				});
			},
			initialAudioPlayer() {
				this.audioPlayer.innerAudioContext = uni.createInnerAudioContext();
				this.audioPlayer.innerAudioContext.onEnded(() => {
					this.audioPlayer.playingMessage = null;
				});
				this.audioPlayer.innerAudioContext.onStop(() => {
					this.audioPlayer.playingMessage = null;
				});
			},
			initRecorderListeners() {
				recorderManager.onRecordComplete((file, duration) => {
					if (duration < 1000) {
						uni.showToast({
							icon: 'none',
							title: '录音时间太短',
							duration: 500
						});
						return;
					}
					GoEasy.im.createAudioMessage({
						to: this.to,
						file: file,
						notification: {
							title: this.currentUser.name + '发来一段语音',
							body: '[语音消息]', // 字段最长 50 字符
							sound: 'message',
							badge: '+1'
						},
						onProgress: function(progress) {
							console.log(progress)
						},
						onSuccess: (message) => {
							this.sendMessage(message);
						},
						onFailed: (e) => {
							console.log('error :', e);
						}
					});
				});
			},
			/**
			 * 核心就是设置高度，产生明确占位
			 *
			 * 小  (宽度和高度都小于预设尺寸)
			 *    设高=原始高度
			 * 宽 (宽度>高度)
			 *    高度= 根据宽度等比缩放
			 * 窄  (宽度<高度)或方(宽度=高度)
			 *    设高=MAX height
			 *
			 * @param width,height
			 * @returns number
			 */
			getImageHeight(width, height) {
				if (width < IMAGE_MAX_WIDTH && height < IMAGE_MAX_HEIGHT) {
					return height * 2;
				} else if (width > height) {
					return (IMAGE_MAX_WIDTH / width * height) * 2;
				} else if (width === height || width < height) {
					return IMAGE_MAX_HEIGHT * 2;
				}
			},
			sendMessage(message) {
				this.history.messages.push(message);
				this.scrollToBottom();
				GoEasy.im.sendMessage({
					message: message,
					onSuccess: function(message) {
						console.log('发送成功.', message);
					},
					onFailed: function(error) {
						if (error.code === 507) {
							console.log(
								'发送语音/图片/视频/文件失败，没有配置OSS存储，详情参考：https://docs.goeasy.io/2.x/im/message/media/alioss'
							);
						} else {
							console.log('发送失败:', error);
						}
					}
				});
			},
			sendTextMessage() {
				if (this.text.trim() !== '') {
					let body = this.text;
					if (this.text.length >= 50) {
						body = this.text.substring(0, 30) + '...';
					}
					GoEasy.im.createTextMessage({
						text: this.text,
						to: this.to,
						notification: {
							title: this.currentUser.name + '发来一段文字',
							body: body,
							sound: 'message',
							badge: '+1'
						},
						onSuccess: (message) => {
							this.sendMessage(message);
						},
						onFailed: (e) => {
							console.log('error :', e);
						}
					});
				}
				this.text = '';
			},
			sendVideoMessage() {
				uni.chooseVideo({
					success: (res) => {
						GoEasy.im.createVideoMessage({
							to: this.to,
							file: res,
							notification: {
								title: this.currentUser.name + '发来一个视频',
								body: '[视频消息]', // 字段最长 50 字符
								sound: 'message',
								badge: '+1'
							},
							onProgress: function(progress) {
								console.log(progress)
							},
							onSuccess: (message) => {
								this.otherTypesMessagePanelVisible = false;
								this.sendMessage(message);
							},
							onFailed: (e) => {
								console.log('error :', e);
							}
						});
					}
				})
			},
			sendImageMessage() {
				const that = this
				uni.chooseImage({
					count: 9,
					success: (res) => {
						res.tempFiles.forEach((file) => {
							uni.uploadFile({
								url: BASE_URL + '/Common/UploadImagesNoAuth',
								filePath: file.path,
								success(res) {
									const {
										data,
										status
									} = JSON.parse(res.data)
									if (status) {
										GoEasy.im.createCustomMessage({
											type: 'newImage', //消息类型
											payload: {
												image: data.src,
												thumbnailImage: data.src
											},
											notification: {
												title: that.currentUser.name +
													'发来一张图片',
												body: '[图片消息]', // 字段最长 50 字符
												sound: 'message',
												badge: '+1'
											},
											to: that.to,
											onSuccess: (message) => {
												that.sendMessage(message);
												that.otherTypesMessagePanelVisible =
													false
											},
										});
									}
								}
							})
							// GoEasy.im.createImageMessage({
							// 	to: this.to,
							// 	file: file,
							// 	notification: {
							// title: this.currentUser.name + '发来一张图片',
							// body: '[图片消息]', // 字段最长 50 字符
							// sound: 'message',
							// badge: '+1'
							// 	},
							// 	onProgress: function(progress) {
							// 		console.log(progress)
							// 	},
							// 	onSuccess: (message) => {
							// 		this.otherTypesMessagePanelVisible = false;
							// 		this.sendMessage(message);
							// 	},
							// 	onFailed: (e) => {
							// 		console.log('error :', e);
							// 	}
							// });
						})
					}
				});
			},
			sendOrderMessage(order) {
				//GoEasyIM自定义消息,实现订单发送
				GoEasy.im.createCustomMessage({
					type: 'order',
					payload: order,
					to: this.to,
					notification: {
						title: this.currentUser.name + '发来一个订单',
						body: '[订单消息]',
						sound: 'message',
						badge: '+1'
					},
					onSuccess: (message) => {
						this.otherTypesMessagePanelVisible = false;
						this.sendMessage(message);
					},
					onFailed: (e) => {
						console.log('error :', e);
					}
				});
				this.orderList.visible = false;
			},
			showActionPopup(message) {
				const MAX_RECALLABLE_TIME = 3 * 60 * 1000; //3分钟以内的消息才可以撤回
				this.messageSelector.messages = [message];
				if ((Date.now() - message.timestamp) < MAX_RECALLABLE_TIME && message.senderId === this.currentUser.id &&
					message.status === 'success') {
					this.actionPopup.recallable = true;
				} else {
					this.actionPopup.recallable = false;
				}
				this.actionPopup.visible = true;
			},
			hideActionPopup() {
				this.actionPopup.visible = false;
				this.actionPopup.message = null;
			},
			deleteSingleMessage() {
				uni.showModal({
					content: '确认删除？',
					success: (res) => {
						this.actionPopup.visible = false;
						if (res.confirm) {
							this.deleteMessage();
						}
					},
				})
			},
			deleteMultipleMessages() {
				if (this.messageSelector.messages.length > 0) {
					uni.showModal({
						content: '确认删除？',
						success: (res) => {
							this.messageSelector.visible = false;
							if (res.confirm) {
								this.deleteMessage();
							}
						},
					})
				}
			},
			deleteMessage() {
				GoEasy.im.deleteMessage({
					messages: this.messageSelector.messages,
					onSuccess: (result) => {
						this.messageSelector.messages.forEach(message => {
							let index = this.history.messages.indexOf(message);
							if (index > -1) {
								this.history.messages.splice(index, 1);
							}
						});
						this.messageSelector.messages = [];
					},
					onFailed: (error) => {
						console.log('error:', error);
					}
				});
			},
			recallMessage() { // 撤回
				this.actionPopup.visible = false;
				GoEasy.im.recallMessage({
					messages: this.messageSelector.messages,
					onSuccess: () => {
						console.log('撤回成功');
					},
					onFailed: (error) => {
						console.log('撤回失败,error:', error);
					}
				});
			},
			handleDownloadImg() { // 下载图片
				const msg = this.messageSelector.messages[0]
				const imgUrl = msg.payload.image
				const that = this

				const systemInfo = uni.getSystemInfoSync();
				console.log(systemInfo);
				if (systemInfo.platform == 'ios') {
					// 苹果设备
					uni.downloadFile({
						url: imgUrl,
						success(e) {
							window.open(e.tempFilePath)
						}
					})
				} else {
					// 安卓设备,
					fetch(imgUrl)
						.then(response => response.blob())
						.then(blob => {
							const url = window.URL.createObjectURL(blob);
							const a = document.createElement('a');
							a.style.display = 'none';
							a.href = url;
							a.download = `型格目录-${this.group.name}-${new Date().getTime()}`; // 设置下载文件的名称
							document.body.appendChild(a);
							a.click();
							window.URL.revokeObjectURL(url);
							uni.showToast({
								title: '图片下载成功'
							})
							that.actionPopup.visible = false;
							that.actionPopup.message = null;
						})
						.catch(error => {
							uni.showToast({
								icon: 'error',
								title: error
							})
							console.error('Error downloading the file:', error);
						});
				}

			},
			editRecalledMessage(text) {
				if (this.audio.visible) {
					this.audio.visible = false;
				}
				this.text = text;
			},
			showCheckBox() {
				this.messageSelector.messages = [];
				this.messageSelector.visible = true;
				this.actionPopup.visible = false;
			},
			selectMessages(e) {
				const selectedMessageIds = e.detail.value;
				let selectedMessages = [];
				this.history.messages.forEach(message => {
					if (selectedMessageIds.includes(message.messageId)) {
						selectedMessages.push(message);
					}
				})
				this.messageSelector.messages = selectedMessages;
			},
			// loadHistoryMessage(scrollToBottom) { //历史消息
			// 	this.history.loading = true;
			// 	let lastMessageTimeStamp = null;
			// 	let lastMessage = this.history.messages[0];
			// 	if (lastMessage) {
			// 		lastMessageTimeStamp = lastMessage.timestamp;
			// 	}
			// 	GoEasy.im.history({
			// 		id: this.group.id,
			// 		type: GoEasy.IM_SCENE.GROUP,
			// 		lastTimestamp: lastMessageTimeStamp,
			// 		limit: 10,
			// 		onSuccess: (result) => {
			// 			uni.stopPullDownRefresh();
			// 			this.history.loading = false;
			// 			let messages = result.content;
			// 			if (messages.length === 0) {
			// 				this.history.allLoaded = true;
			// 			} else {
			// 				if (lastMessageTimeStamp) {
			// 					this.history.messages = messages.concat(this.history.messages);
			// 				} else {
			// 					this.history.messages = messages;
			// 				}
			// 				if (messages.length < 10) {
			// 					this.history.allLoaded = true;
			// 				}
			// 				if (scrollToBottom) {
			// 					this.scrollToBottom();
			// 					//收到的消息设置为已读
			// 					this.markGroupMessageAsRead();
			// 				}
			// 			}
			// 		},
			// 		onFailed: (error) => {
			// 			//获取失败
			// 			console.log('获取历史消息失败:', error);
			// 			uni.stopPullDownRefresh();
			// 			this.history.loading = false;
			// 		}
			// 	});

			// 	// 在加载完成后：
			// 	this.$nextTick(() => {
			// 		if (scrollToBottom) {
			// 			this.scrollToBottom();
			// 		} else {
			// 			// 保持滚动位置不变
			// 			const query = uni.createSelectorQuery().in(this);
			// 			query.select('.scroll-view').boundingClientRect(data => {
			// 				this.scrollTop = data.scrollTop;
			// 			}).exec();
			// 		}
			// 	});
			// },
			async loadHistoryMessage(scrollToBottom) {
				if (this.isLoadingMore) return;
				const that = this
				this.isLoadingMore = true;
				this.history.loading = true;

				try {
					let lastMessageTimeStamp = null;
					let lastMessage = this.history.messages[0];
					if (lastMessage) {
						lastMessageTimeStamp = lastMessage.timestamp;
					}

					await GoEasy.im.history({
						id: this.group?.id,
						type: GoEasy.IM_SCENE.GROUP,
						lastTimestamp: lastMessageTimeStamp,
						limit: 10,
						onSuccess: (result) => {
							uni.stopPullDownRefresh();
							this.history.loading = false;
							let messages = result.content;

							if (messages.length === 0) {
								this.history.allLoaded = true;
							} else {
								if (lastMessageTimeStamp) {
									this.history.messages = messages.concat(this.history.messages);
									// 在下一个渲染周期恢复滚动位置
								} else {
									this.history.messages = messages;
								}

								if (messages.length < 10) {
									this.history.allLoaded = true;
								}

								this.$nextTick(() => {
									if (scrollToBottom) {
										this.scrollToBottom();
									}
								});
							}
						},
						onFailed: (error) => {
							console.log('获取历史消息失败:', error);
							uni.stopPullDownRefresh();
						}
					});
				} finally {
					this.history.loading = false;
					this.isLoadingMore = false;
				}
			},
			showMembers() { //显示群成员
				uni.navigateTo({
					url: './member?members=' + JSON.stringify(this.groupMembers)
				});
			},
			onRecordStart() {
				recorderManager.start();
			},
			onRecordEnd() {
				recorderManager.stop();
			},
			showImageFullScreen(e) {
				let imagesUrl = [e.currentTarget.dataset.url];
				uni.previewImage({
					urls: imagesUrl
				});
			},
			//语音录制按钮和键盘输入的切换
			switchAudioKeyboard() {
				if (!this.audio.visible) {
					recorderManager.authorize().then(() => {
						console.log('录音权限获取成功');
						this.audio.visible = true;
					}).catch((err) => {
						console.log('err:', err)
						uni.showModal({
							title: '获取录音权限失败',
							content: '请先打开麦克风权限'
						});
					});
				} else {
					this.audio.visible = false;
				}
			},
			playVideo(e) {
				this.videoPlayer.visible = true;
				this.videoPlayer.url = e.currentTarget.dataset.url;
				this.$nextTick(() => {
					this.videoPlayer.context.requestFullScreen({
						direction: 0
					});
					this.videoPlayer.context.play();
				});
			},
			playAudio(audioMessage) {
				let playingMessage = this.audioPlayer.playingMessage;

				if (playingMessage) {
					this.audioPlayer.innerAudioContext.stop();
					// 如果点击的消息正在播放，就认为是停止播放操作
					if (playingMessage === audioMessage) {
						return;
					}
				}
				this.audioPlayer.playingMessage = audioMessage;
				this.audioPlayer.innerAudioContext.src = audioMessage.payload.url;
				this.audioPlayer.innerAudioContext.play();
			},
			onVideoFullScreenChange(e) {
				//当退出全屏播放时，隐藏播放器
				if (this.videoPlayer.visible && !e.detail.fullScreen) {
					this.videoPlayer.visible = false;
					this.videoPlayer.context.stop();
				}
			},
			messageInputFocusin() {
				this.otherTypesMessagePanelVisible = false;
				this.emoji.visible = false;
			},
			switchEmojiKeyboard() {
				this.emoji.visible = !this.emoji.visible;
				this.otherTypesMessagePanelVisible = false;
			},
			showOtherTypesMessagePanel() {
				this.otherTypesMessagePanelVisible = !this.otherTypesMessagePanelVisible;
				this.emoji.visible = false;
			},
			chooseEmoji(emojiKey) {
				this.text += emojiKey;
			},
			showOrderMessageList() {
				this.orderList.orders = restApi.getOrderList();
				this.orderList.visible = true;
			},
			hideOrderMessageList() {
				this.orderList.visible = false;
			},
			groupCall() {
				uni.showActionSheet({
					itemList: ['视频通话', '语音通话'],
					success: (res) => {
						const mediaType = res.tapIndex === 0 ? 1 : 0;
						uni.navigateTo({
							url: `./rtc/group/chooseCallee?mediaType=${mediaType}&groupId=${this.group.id}`,
						})
					},
					fail: (res) => {
						console.log(res.errMsg);
					}
				});
			},
			scrollToBottom() {
				this.$nextTick(() => {
					if (this.history.messages.length > 0) {
						const lastMessageLen = this.history.messages.length;
						this.scrollToView = `msg_${lastMessageLen}`
					}
				});
				// this.$nextTick(() => {
				// 	const query = uni.createSelectorQuery().in(this);
				// 	query.select('.scroll-view').boundingClientRect(data => {
				// 		this.scrollTop = data.scrollHeight;
				// 		this.lastContentHeight = data.scrollHeight;
				// 	}).exec();
				// });
			},
			markGroupMessageAsRead() {
				GoEasy.im.markMessageAsRead({
					id: this.to.id,
					type: this.to.type,
					onSuccess: function() {
						console.log('标记群聊已读成功');
					},
					onFailed: function(error) {
						console.log('标记群聊已读失败:', error);
					}
				})
			}
		}
	}
</script>

<style>
	@import url('../static/style/chatInterface.css');
</style>